package com.wmh.baseservice.robot.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wmh.baseservice.common.mybatisplus.EntityUtil;
import com.wmh.baseservice.common.utils.ServletUtils;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.web.UserUtil;
import com.wmh.baseservice.robot.entity.RobotTaskStatementV2;
import com.wmh.baseservice.robot.enums.TaskStatus;
import com.wmh.baseservice.robot.pojo.dto.TaskStatementFileReps;
import com.wmh.baseservice.robot.pojo.vo.taskstatement.TaskStatementPageReqV2VO;
import com.wmh.baseservice.robot.service.RobotTaskStatementV2Service;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.success;

/**
 * @author 谢骏
 * @date 2023/9/13 16:25
 **/
@Api(tags = "自动化机器-任务报表相关接口v2", value = "任务报表相关接口v2")
@RestController
@RequestMapping("robot/statement-v2")
@Validated
public class RobotTaskStatementV2Controller {

    @Resource
    private UserUtil userUtil;

    @Resource
    private RobotTaskStatementV2Service robotTaskStatementV2Service;


    @ApiOperation(value = "删除")
    @PostMapping("delete")
    public String delete(@NotNull(message = "未提交主键") @Size(min = 1, message = "未提交主键") @RequestBody List<Long> ids) {
        robotTaskStatementV2Service.removeByIds(ids);
        return success();
    }

    @ApiOperation("分页")
    @GetMapping("page")
    public String page(@Valid TaskStatementPageReqV2VO reqVO) {
        boolean superAdmin = userUtil.isSuperAdmin();
        String[] resultField = EntityUtil.getFieldValuesWithPrefix(RobotTaskStatementV2.class, "COL_",
                RobotTaskStatementV2.COL_TASK_FILE_BASE64, RobotTaskStatementV2.COL_TASK_LOG_BASE64).toArray(new String[0]);
        PageResult<RobotTaskStatementV2> pageResult = new PageUtil<RobotTaskStatementV2>(reqVO).startPage((page, queryWrapper) -> {
            queryWrapper.select(resultField);
            LambdaQueryWrapper<RobotTaskStatementV2> l = queryWrapper.lambda();
            l.eq(reqVO.getStatementId() != null, RobotTaskStatementV2::getId, reqVO.getStatementId())
                    .eq(reqVO.getTaskStatus() != null, RobotTaskStatementV2::getTaskStatus, reqVO.getTaskStatus())
                    .eq(reqVO.getPushUnitId() != null, RobotTaskStatementV2::getPushTaskUnitId, reqVO.getPushUnitId())
                    .eq(reqVO.getTaskId() != null, RobotTaskStatementV2::getTaskId, reqVO.getTaskId())
                    .eq(reqVO.getRobotNumber() != null, RobotTaskStatementV2::getRobotNumber, reqVO.getRobotNumber())
                    .eq(reqVO.getPushTaskType() != null, RobotTaskStatementV2::getTaskType, reqVO.getPushTaskType())
                    .like(StrUtil.isNotBlank(reqVO.getTaskName()), RobotTaskStatementV2::getTaskName, reqVO.getTaskName())
                    .like(StrUtil.isNotBlank(reqVO.getPushUnitName()), RobotTaskStatementV2::getPushTaskUnitName, reqVO.getPushUnitName());
            if (superAdmin) {
                l.eq(reqVO.getLookMe(), RobotTaskStatementV2::getAdId, userUtil.getId());
                l.eq(!reqVO.getLookMe() && reqVO.getAdId() != null, RobotTaskStatementV2::getAdId, reqVO.getAdId());
            } else {
                l.eq(RobotTaskStatementV2::getAdId, userUtil.getId());
            }
            l.orderByDesc(RobotTaskStatementV2::getCreateTime);
            robotTaskStatementV2Service.page(page, queryWrapper);
        });
        return success(pageResult);
    }

    @ApiOperation("任务状态选项")
    @GetMapping("statusOptions")
    public String statusOptions() {
        return success(
                Arrays.stream(TaskStatus.values()).map(item ->
                        JSONObject.of("label", item.getLabel(), "value", item.getValue())
                ).collect(Collectors.toList())
        );
    }

    @ApiOperation("下载报表")
    @GetMapping("dwFile")
    @RequiresPermissions("robot.taskStatement.dwFile")
    public void dwFile(@NotNull(message = "未提交主键") Long id, HttpServletResponse response) throws IOException {
        // 获取文件响应对象
        TaskStatementFileReps taskStatementFile = robotTaskStatementV2Service.getTaskStatementFile(id);
        // 输出
        ServletUtils.writeAttachment(response, taskStatementFile.getFileFullName(), taskStatementFile.getContent());
    }

    @ApiOperation(value = "下载任务日志附件")
    @GetMapping("dwLog")
    @RequiresPermissions("robot.taskStatement.dwLog")
    public void dwLog(@NotNull(message = "未提交主键") Long id, HttpServletResponse response) throws IOException {
        // 获取文件响应对象
        TaskStatementFileReps taskStatementFile = robotTaskStatementV2Service.getTaskStatementLog(id);
        // 输出
        ServletUtils.writeAttachment(response, taskStatementFile.getFileFullName(), taskStatementFile.getContent());
    }
}
